Zigzag Traversal (medium)
We'll cover the following
Problem Statement #
Given a binary tree, populate an array to represent its zigzag level order traversal. You should populate the values of all nodes of the first level from left to right, then right to left for the next level and keep alternating in the same manner for the following levels.
Example 1:
Example 2:
Try it yourself #
Try solving this question here:
Solution #
This problem follows the Binary Tree Level Order Traversal pattern. We can follow the same BFS approach. The only additional step we have to keep in mind is to alternate the level order traversal, which means that for every other level, we will traverse similar to Reverse Level Order Traversal.
Code #
Here is what our algorithm will look like, only the highlighted lines have changed:
Time complexity #
The time complexity of the above algorithm is , where āNā is the total number of nodes in the tree. This is due to the fact that we traverse each node once.
Space complexity #
The space complexity of the above algorithm will be as we need to return a list containing the level order traversal. We will also need space for the queue. Since we can have a maximum of nodes at any level (this could happen only at the lowest level), therefore we will need space to store them in the queue.